// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include <unordered_map>
#include "commoncppproblem652.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=652 lang=cpp
 *
 * [652] 寻找重复的子树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    string travel(TreeNode* root,unordered_map<string,int> &memo,vector<TreeNode*> &res)
    {
        if(root == NULL)
            return "#";
        string left = travel(root->left,memo,res);
        string right = travel(root->right,memo,res);

        char val[10] = {0};
        snprintf(val,sizeof(val),"%d",root->val);
        string subTree = left + "," + right + "," + val;
        memo[subTree]++;
       
        
        if(memo[subTree] == 1)
        {
            res.push_back(root);
        }
        
        return subTree;
    }


    vector<TreeNode*> findDuplicateSubtrees(TreeNode* root) {
        unordered_map<string,int> memo;         //记录所有的子树以及出现的次数
        vector<TreeNode*> res;                  //记录重复的子树根节点
        travel(root,memo,res);
        return res;

    }
};
// @lc code=end

